import React, { useState, useCallback, useEffect } from 'react';
import classnames from 'classnames';
import _ from 'lodash';

import loadingSVG from './loading';

// import './button.scss';

type ButtonPropsType = {
  disabled?: boolean,
  size?: ('sm' | 'md' | 'lg'),
  children?: React.ReactNode,
  type?: ('primary' | 'success' | 'danger' | 'warning' | 'default' | 'link'),
  htmlType?: ('button' | 'submit' | 'reset'),
  onClick?: (evt: React.MouseEvent) => void,
  block?: boolean,
  icon?: React.ReactNode,
  loading?: boolean;
}

const isTwoChinese = (str: string): boolean => /^[\u4e00-\u9fa5]{2}$/.test(str);

const nullFn = () => { };

const active = _.throttle((setClassNames: Function) => {
  setClassNames((classNames: string) => {
    setTimeout(() => {
      setClassNames((clsNames: string) => {
        return clsNames.split(' ').filter(item => item !== 'mute-btn-active').join(' ');
      })
    }, 800)
    return classNames + ' mute-btn-active';
  });
}, 800);

const Button = (props: ButtonPropsType): JSX.Element => {

  const {
    children = 'Button',
    size = 'md',
    type = 'default',
    disabled = false,
    htmlType = 'button',
    block = false,
    icon,
    loading,
    onClick = nullFn,
  } = props;

  const [classNames, setClassNames] = useState(classnames({
    'mute-btn': true,
    'mute-btn-small': size === 'sm',
    'mute-btn-large': size === 'lg',
    'mute-btn-danger': type === 'danger',
    'mute-btn-success': type === 'success',
    'mute-btn-warning': type === 'warning',
    'mute-btn-primary': type === 'primary',
    'mute-btn-default': type === 'default',
    'mute-btn-link': type === 'link',
    'mute-btn-block': block,
    'mute-btn-loading': type === 'link' ? false : loading,
  }));

  useEffect(() => {
    if (loading) {
      setClassNames((classNames: string) => classNames + ' mute-btn-loading')
    } else {
      setClassNames((clsNames: string) => clsNames.split(' ').filter(item => item !== 'mute-btn-loading').join(' '))
    }
  }, [loading]);
  
  const showActive = useCallback(() => {
    !loading && active(setClassNames);
  }, [loading])

  let text = '';
  if (typeof children === 'string' && isTwoChinese(children)) {
    text = children[0] + ' ' + children[1];
  }
  
  return (
    <button
      className={classNames}
      disabled={disabled}
      onClick={disabled || loading ? nullFn : onClick}
      onMouseUp={disabled ? nullFn : showActive}
      type={htmlType}
    >
      <span className="mute-btn-text">
        {
          (icon || loading) && (
            <span className="mute-btn-icon">
              <i>{
                loading && type !== 'link' ? 
                loadingSVG()
                : icon
              }</i>
            </span>
          )
        }
        <span>
          {text || children}
        </span>
      </span>
    </button>
  )
}

export default Button;